import React, { useEffect, useRef, useState } from "react";
import { Alert, Anchor, Form, message } from "antd";
import './index.less';
import CompanyInfo from "./modules/CompanyInfo";
import SendInfo from "./modules/SendInfo";
import ProductInfo from "./modules/ProductInfo";
import GoodsInfo from "./modules/GoodsInfo";
import OtherInfo from "./modules/OtherInfo";
import FeeInfo from "./modules/FeeInfo";
import OrderFeePreview from "./modules/OrderFeePreview";
import { orderTypes, preOrderTypes } from "@/constants/types";
import { useModel, useLocation } from "@umijs/max";
import { useRequest } from "ahooks";
import { placeOrder, intendedOrdertransformOrder, fetchOrderDetail } from '../services';
import { isEmptyObj } from "@/utils/util";

const OrderCreate = () => {
  const { getDict } = useModel('dictModel');


  const location = useLocation();
  const searchParams = new URLSearchParams(location.search);
  const orderId = searchParams.get('orderId');
  const preOrderId = searchParams.get('preOrderId');
  const isReOrder = !!searchParams.get('isReOrder');
  const isPreOrderConvertOrder = !!preOrderId;


  const orderWrapper = useRef();
  const [companyInfoForm] = Form.useForm();
  const [sendInfoForm] = Form.useForm();
  const [productInfoForm] = Form.useForm();
  const [goodsInfoForm] = Form.useForm();
  const [otherInfoForm] = Form.useForm();
  const [feeInfoForm] = Form.useForm();

  // 
  const [step, setStep] = useState<string>('#companyInfo');
  const [msg, setMsg] = useState<string>('');

  // 再来一单或者意向单的数据
  const [originData, setOriginData] = useState<orderTypes | null | preOrderTypes>(null);

  // 
  const {loading: placeOrderLoading, runAsync: placeOrderApi} = useRequest(placeOrder, {manual: true});


  // 公共属性
  const contentProps = {
    originData,
    isReOrder,
    isPreOrderConvertOrder,
    preOrderId,
    orderId,
    showMsg: (message: string) => {
      setMsg(message);
    },
    getDict,
  }

  // 模块
  const tabs = [
    {
      title: <div className={step === "#companyInfo" ? 'nav-item checked' : "nav-item"}>下单账户</div>,
      key: 'companyInfo',
      href:"#companyInfo",
    },
    {
      title: <div className={step === "#sendInfo" ? 'nav-item checked' : "nav-item"}>收发地址信息</div>,
      key: 'sendInfo',
      href:"#sendInfo",
    },
    {
      title: <div className={step === "#productInfo" ? 'nav-item checked' : "nav-item"}>渠道/产品</div>,
      key: 'productInfo',
      href:"#productInfo",
      label: '渠道/产品',
    },
    {
      title: <div className={step === "#goodsInfo" ? 'nav-item checked' : "nav-item"}>货物/产品信息</div>,
      key: 'goodsInfo',
      href:"#goodsInfo",
    },
    {
      title: <div className={step === "#otherInfo" ? 'nav-item checked' : "nav-item"}>其他信息</div>,
      key: 'otherInfo',
      href:"#otherInfo",
    },
    {
      title: <div className={step === "#feeInfo" ? 'nav-item checked' : "nav-item"}>报价及费用预估</div>,
      key: 'feeInfo',
      href:"#feeInfo",
    },
  ];

  const onSubmit = async (params: any) => {
    const res = await placeOrderApi(params);
    if (res?.code === '0') {
      message.success('操作成功!');
      window.location.href = "/order-manage/order-list"
    }
  }
  // 参数设置到页面
  const paramsSetToPage = (info: orderTypes | preOrderTypes) => {
    setOriginData(info || null);
    if (!isEmptyObj(info)) {
      companyInfoForm.setFieldsValue({
        contacts: info?.contacts,
        mobile: info?.mobile,
        userId: info?.userId,
        customerName: info?.customerName,
        customerCode: info?.customerCode,
        companyContactMobile: info?.userId
      });
      sendInfoForm.setFieldsValue({
        ...info,
        pickupWay: isPreOrderConvertOrder ? info?.pickupWay : info?.pickupMethod, // 意向单位 pickupWay
        pickupArea: info?.pickupProvince && info?.pickupCity && info?.pickupArea ? [info?.pickupProvince, info?.pickupCity, info?.pickupArea] : [],
        pickUpDateTime: {
          date: info?.appointPickupDate,
          time: info?.appointPickupTime,
        }
      });
      productInfoForm.setFieldsValue({
        product: info?.product,
        deliveryMethod: info?.deliveryMethod,
        quoteId: info?.quoteId,
        dportCode: info?.dportCode,
      });
      goodsInfoForm.setFieldsValue({
        cargoName: info?.cargoName,
        totalPieces: info?.totalPieces,
        totalWeight: info?.totalWeight,
        totalVol: info?.totalVol,
        shipmentId: info?.shipmentId,
        // entrustFilePath: info?.entrustFilePath,
      });
      otherInfoForm.setFieldsValue(info);
      feeInfoForm.setFieldsValue({
        ...info,
        orderCode: isPreOrderConvertOrder ? info?.code : isReOrder ? undefined : info?.orderCode
      });
    }
  }
  // 获取提交参数
  const getParams = () => {
    const companyInfo = companyInfoForm.getFieldsValue();
    const sendInfo = sendInfoForm.getFieldsValue();
    const productInfo = productInfoForm.getFieldsValue();
    const goodsInfo = goodsInfoForm.getFieldsValue();
    const otherInfo = otherInfoForm.getFieldsValue();
    const feeInfo = feeInfoForm.getFieldsValue();

    return {
      intendedOrderId: preOrderId,
      id: (orderId && !isReOrder) ? orderId : undefined,
      ...companyInfo,
      ...sendInfo,
      ...productInfo,
      ...goodsInfo,
      ...otherInfo,
      ...feeInfo,
      pickupProvince: sendInfo?.pickupArea?.[0],
      pickupCity: sendInfo?.pickupArea?.[1],
      pickupArea: sendInfo?.pickupArea?.[2],
      appointPickupDate: sendInfo?.pickUpDateTime?.date,
      appointPickupTime: sendInfo?.pickUpDateTime?.time,
      pickUpDateTime: undefined,
      entrustFilePath: goodsInfo?.entrustFilePath?.[0]?.response,
      entrustFileName: goodsInfo?.entrustFilePath?.[0]?.response?.split('/')?.pop(),
      customsFilePath: otherInfo?.customsFilePath?.[0]?.response,
      customsFileName: otherInfo?.customsFilePath?.[0]?.response?.split('/')?.pop(),
      mode: '0',
      orderCode: undefined
    }
  }

  // 提交
  const handleSubmit = async () => {
    await companyInfoForm.validateFields();
    await sendInfoForm.validateFields();
    await productInfoForm.validateFields();
    await goodsInfoForm.validateFields();
    await otherInfoForm.validateFields();
    await feeInfoForm.validateFields();
    onSubmit({
      ...getParams(),
      mode: '1'
    });
  }
  // 草稿
  const handleSaveSubmit = () => {
    onSubmit({
      ...getParams(),
      mode: '0'
    });
  }

  // useEffect(() => {
  //   // 锚点滚动区域
  //   if (orderWrapper?.current?.scrollTop !== undefined) {
  //     const scrollTop = tabs.find(v => v.value === step)?.scrollTop;
  //     orderWrapper.current.scrollTop = scrollTop;
  //   }
  // }, [step]);

  const handleChange = (link) => {
    setStep(link || "#companyInfo");
  }


  useEffect(() => {
    if (preOrderId) {
      intendedOrdertransformOrder({id: preOrderId}).then(
        res => {
          if (res?.code === '0') {
            paramsSetToPage(res?.data || null);
          }
        }
      )
    } else {
      companyInfoForm.resetFields();
      sendInfoForm.resetFields();
      productInfoForm.resetFields();
      goodsInfoForm.resetFields();
      otherInfoForm.resetFields();
      feeInfoForm.resetFields();
    }
  }, [preOrderId]);

  useEffect(() => {
    if (orderId) {
      fetchOrderDetail({id: orderId}).then(
        res => {
          paramsSetToPage(res || null);
        }
      )
    } else {
      companyInfoForm.resetFields();
      sendInfoForm.resetFields();
      productInfoForm.resetFields();
      goodsInfoForm.resetFields();
      otherInfoForm.resetFields();
      feeInfoForm.resetFields();
    }
  }, [orderId])

  return (
    <>
      <div className="order-wrapper">
        <div className="order-left">
          <div className="nav">
            {/* {
              tabs?.map(v => (
                <div onClick={() => setStep(v.value)} key={v.value} className={step === v.value ? 'nav-item checked' : 'nav-item'}>{v.label}</div>
              ))
            } */}
            <Anchor onChange={handleChange} items={tabs} />
          </div>
        </div>
        <div className="order-content" ref={orderWrapper}>
          {msg && <Alert className="order-msg" type="warning" message={<div style={{fontSize: '18px', color: '#A30014'}}>{msg}</div>} />}
          {/* 下单账户 */}
          <div id="companyInfo">
            <CompanyInfo form={companyInfoForm} {...contentProps} />
          </div>
          {/* 收发地址信息 */}
          <div id="sendInfo">
            <SendInfo form={sendInfoForm} productInfoForm={productInfoForm} companyInfoForm={companyInfoForm} {...contentProps} />
          </div>
          {/* 渠道/产品 */}
          <div id="productInfo">
            <ProductInfo form={productInfoForm} {...contentProps} sendInfoForm={sendInfoForm} />
          </div>
          {/* 货物/产品信息 */}
          <div id="goodsInfo">
            <GoodsInfo form={goodsInfoForm} {...contentProps} />
          </div>
          {/* 其他信息 */}
          <div id="otherInfo">
            <OtherInfo 
              form={otherInfoForm}
              productInfoForm={productInfoForm}
              goodsInfoForm={goodsInfoForm} 
              {...contentProps}
            />
          </div>
          {/* 报价费用信息 */}
          <div id="feeInfo">
            <FeeInfo 
              companyInfoForm={companyInfoForm}
              sendInfoForm={sendInfoForm} 
              productInfoForm={productInfoForm}
              goodsInfoForm={goodsInfoForm}
              otherInfoForm={otherInfoForm}
              form={feeInfoForm}
              {...contentProps}
            />
          </div>
          {/* 订单预览 */}
          <OrderFeePreview
            companyInfoForm={companyInfoForm}
            sendInfoForm={sendInfoForm} 
            productInfoForm={productInfoForm}
            goodsInfoForm={goodsInfoForm}
            otherInfoForm={otherInfoForm}
            feeInfoForm={feeInfoForm}
            isPreOrderConvertOrder={isPreOrderConvertOrder}
            loading={placeOrderLoading}
            onSave={handleSaveSubmit}
            onSubmit={handleSubmit}
            getParams={getParams}
          />
        </div>
      </div>
    </>
  );
}
export default OrderCreate;